<template>
    <div class="container">
        <el-card class="card">
            <div class="header">
                <el-button v-for="(item, index) in dateOptions" :key="index" @click="selectDate(item.value)">
                    {{ item.label }}
                </el-button>
            </div>
            <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="100px"
                label-position="left">
                <el-row :gutter="15">
                    <el-col :span="7">
                        <el-form-item label="出库单号" prop="outboundCode">
                            <el-input v-model="formData.outboundCode" placeholder="请输入入库单号" clearable
                                :style="{ width: '100%' }">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="出库类型" prop="outboundType">
                            <el-select v-model="formData.outboundType" placeholder="请选择入库类型" clearable
                                @change="handleInventoryTypeChange" :style="{ width: '100%' }">
                                <el-option v-for="dict in dict.type.py_outbound_type" :key="dict.value"
                                    :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="仓库名称" prop="warehouseId">
                            <el-select v-model="formData.warehouseId" placeholder="请选择" :style="{ width: '100%' }">
                                <el-option v-for="item in warehouseIds" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="货品编号" prop="productCode">
                            <el-input v-model="formData.productCode" placeholder="请输入货品编号" clearable
                                :style="{ width: '100%' }">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="单位" prop="productUnit">
                            <el-select v-model="formData.productUnit" placeholder="请选择入库类型" clearable
                                @change="handleInventoryTypeChange" :style="{ width: '100%' }">
                                <el-option v-for="dict in dict.type.py_product_unit" :key="dict.value"
                                    :label="dict.label" :value="dict.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="出库时间">
                            <el-date-picker v-model="formData.outDateList" type="daterange" start-placeholder="开始日期"
                                end-placeholder="结束日期" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="10" style="margin-top: 0px;">
                    <!-- <el-col :span="7">
                        <el-form-item label="制单人">
                            <el-cascader v-model="formData.creator" :options="cascaderOptions" :props="cascaderProps"
                                placeholder="请选择" @change="handleChange" :style="{ width: '100%' }" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="7">
                        <el-form-item label="制单时间">
                            <el-date-picker v-model="formData.zdDateList" type="daterange" start-placeholder="开始日期"
                                end-placeholder="结束日期" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
            <div class="statistics">
                <el-card class="stat-card" v-for="(stat, index) in statistics" :key="index">
                    <div class="stat-title">{{ stat.title }}</div>
                    <div class="stat-value" :style="{ color: stat.color }">
                        <!-- {{ stat.value }} -->
                        <count-to :start-val="0" :end-val="stat.value" :duration="2600" class="card-panel-num" />
                    </div>
                </el-card>
            </div>

            <el-table :data="tableData" style="width: 100%">
                <el-table-column fixed prop="index" label="序号" width="60"></el-table-column>
                <el-table-column fixed prop="outboundCode" label="出库单号" width="160"></el-table-column>
                <el-table-column fixed prop="outboundTime" label="出库日期" width="150"></el-table-column>
                <el-table-column fixed prop="outboundType" label="出库类型" width="100">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.py_outbound_type" :value="scope.row.outboundType" />
                    </template>
                </el-table-column>
                <el-table-column prop="warehouseName" label="仓库名称" width="120"></el-table-column>
                <el-table-column prop="locationName" label="库位名称" width="120"></el-table-column>
                <el-table-column prop="productCode" label="货品编号" width="160"></el-table-column>
                <el-table-column prop="productName" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="productModel" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="productUnit" label="单位" width="80">
                </el-table-column>
                <el-table-column prop="productTypeName" label="货品类型" width="100"></el-table-column>
                <el-table-column prop="outPrice" label="出库单价" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.outPrice.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="outNumber" label="出库数量" width="100"></el-table-column>
                <el-table-column prop="outMoney" label="出库金额" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.outMoney.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="reviewer" label="经办人" width="100"></el-table-column>
                <el-table-column prop="createBy" label="制单人" width="100"></el-table-column>
                <!-- <el-table-column prop="deptName" label="所在部门" width="100"></el-table-column> -->
                <el-table-column prop="createTime" label="制单时间" width="150"></el-table-column>
                <el-table-column prop="reviewer" label="审核人" width="100"></el-table-column>
                <el-table-column prop="reviewerTime" label="审核时间" width="150">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.reviewerTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="formData.pageNum" :limit.sync="formData.pageSize"
                @pagination="getList" />
        </el-card>
    </div>
</template>

<script>
import {
    selectAllBsWarehouse, WhOutboundLS, selectAllSysUserByParentId, selectAllSysDeptByID, selectAllSysDept, outTotle
} from "@/api/inbound/inbound";
import CountTo from 'vue-count-to'
export default {
    components: { CountTo },
    dicts: ['py_outbound_type', 'py_product_unit'],
    data() {
        return {
            total: 0,
            // jbr: [],
            // // selectedDate: 'today',  // 默认选择  
            // cascaderOptions: [],
            // cascaderProps: {
            //     value: 'value',
            //     label: 'label',
            //     children: 'children',
            //     // checkStrictly: true
            // },
            dateOptions: [
                { label: '今日', value: 'today' },
                { label: '昨日', value: 'yesterday' },
                { label: '本周', value: 'thisWeek' },
                { label: '上月', value: 'lastMonth' },
                { label: '全部', value: '' },
                // { label: '自定义时间', value: 'custom' },
            ],
            formData: {
                pageNum: 1,
                pageSize: 10,
                outboundCode: '',
                outboundType: undefined,//入库类型
                warehouseId: undefined,
                productUnit: undefined,
                productName: '',
                outDateList: [],
                zdDateList: [],
                outboundTime: ''
            },
            warehouseIds: [],//仓库名称id数组
            rules: {},
            statistics: [
                { title: '出库单数量', value: 20, color: '#67C23A' },
                { title: '出库货品数量', value: 30, color: '#E6A23C' },
                { title: '出库货品金额', value: 100, color: '#F56C6C' },
            ],
            tableData: [
            ],
        };
    },
    created() {
   
        this.getList();
        // 确保selectAllBsWarehouse是一个函数并调用它
        selectAllBsWarehouse().then(response => {
            this.warehouseIds = response.data.map(item => ({
                value: item.warehouseId,
                label: item.warehouseName
            }));
        }).catch(error => {
            console.error('Fetching warehouses failed:', error);
        });
        outTotle().then(response => {
            console.log('后端响应阿萨11:', JSON.stringify(response, null, 2));
            this.statistics[0].value = response.outNumber
            this.statistics[1].value = response.reviewerNumber
            this.statistics[2].value = response.outMoney
        }).catch(error => {
            console.error('Fetching warehouses failed:', error);
        });

    },
    methods: {

        handleInventoryTypeChange(newVal) {

        },

        selectDate(value) {
            console.log('选择响应:', value);
            this.formData.outboundTime = value;
            this.getList();
            // 这里可以根据选择的日期更新表格数据  
        },
        search() {
          
            this.formData.pageNum = 1;
            // 执行查询操作  
            console.log('查询数据', this.formData);
            this.getList();
        },
        reset() {

            this.formData = {
                outboundCode: '',
                outboundType: undefined,//入库类型
                warehouseId: undefined,
                productUnit: undefined,
                productName: '',
                outDateList: [],
                zdDateList: [],
                outboundTime: ''
            };
        },
        getList() {
            // this.loading = true;
            WhOutboundLS(this.formData).then(response => {
                console.log('后端响应阿萨:', JSON.stringify(response, null, 2));
                // this.tableData = response.rows;
                this.tableData = response.rows.map((item, index) => ({
                    ...item,
                    index: index + 1
                }));
                this.total = response.total;
                // this.loading = false;
            });
        },
        parseTime(time, format) {
            if (!time) return '';
            const date = new Date(time);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return format.replace(/yyyy/g, year)
                .replace(/MM/g, month)
                .replace(/dd/g, day)
                .replace(/HH/g, hours)
                .replace(/mm/g, minutes)
                .replace(/ss/g, seconds);
        },
        // async fetchItems() {
        //     try {
        //         const response = await selectAllSysDept();
        //         if (Array.isArray(response)) {
        //             this.cascaderOptions = await this.convertToCascaderOptions(response);
        //         } else {
        //             console.error('Expected an array, but got:', response);
        //         }
        //     } catch (error) {
        //         console.error('Error fetching items:', error);
        //     }
        // },

        // async convertToCascaderOptions(data) {
        //     if (!Array.isArray(data)) {
        //         console.error('Expected an array, but got:', data);
        //         return [];
        //     }

        //     // 创建一个映射，用于快速查找父项
        //     const itemMap = new Map(data.map(item => [item.deptId, item]));
        //     const topLevelItems = [];

        //     for (const item of data) {
        //         if (item.parentId === 0) {
        //             topLevelItems.push(await this.createOption(item));
        //         } else {
        //             const parentItem = itemMap.get(item.parentId);
        //             if (parentItem) {
        //                 const childItem = await this.createOption(item);
        //                 if (!parentItem.children) {
        //                     parentItem.children = [];
        //                 }
        //                 parentItem.children.push(childItem);
        //             }
        //         }
        //     }

        //     return topLevelItems;
        // },

        // async createOption(item) {
        //     const [children, users] = await Promise.all([
        //         this.fetchChildren(item.deptId),
        //         this.fetchUsers(item.deptId)
        //     ]);
        //     return {
        //         value: item.deptId,
        //         label: item.deptName,
        //         children: children,
        //         users: users
        //     };
        // },

        // async fetchUsers(deptId) {
        //     try {
        //         const response = await selectAllSysUserByParentId(deptId);
        //         if (Array.isArray(response)) {
        //             return response.map(user => ({
        //                 value: user.userId,
        //                 label: user.userName
        //             }));
        //         } else {
        //             console.error('Expected an array, but got:', response);
        //             return [];
        //         }
        //     } catch (error) {
        //         console.error('Error fetching users:', error);
        //         return [];
        //     }
        // },

        // async fetchChildren(parentId) {
        //     try {
        //         const response = await selectAllSysDeptByID(parentId);
        //         if (Array.isArray(response)) {
        //             return Promise.all(response.map(async (item) => {
        //                 const [users, children] = await Promise.all([
        //                     this.fetchUsers(item.deptId),
        //                     this.fetchChildren(item.deptId) // 递归获取子部门
        //                 ]);
        //                 return {
        //                     value: item.deptId,
        //                     label: item.deptName,
        //                     children: [
        //                         ...children,
        //                         ...users.map(user => ({
        //                             value: user.value,
        //                             label: user.label,
        //                             // isUser: true
        //                         }))
        //                     ]
        //                 };
        //             }));
        //         } else {
        //             console.error('Expected an array, but got:', response);
        //             return [];
        //         }
        //     } catch (error) {
        //         console.error('Error fetching children:', error);
        //         return [];
        //     }
        // },
        // handleChange(value) {
        //     // const currentSelectedValue = value[value.length - 1];
        //     this.jbr = value;
        //     console.log('后端响应:', value);
        // },
    },
};
</script>

<style scoped>
.container {
    padding: 20px;
}

.card {
    padding: 20px;
}

.header {
    margin-bottom: 20px;
}

.form-row {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 10px;
}

.form-row .el-form-item {
    margin-right: 20px;
    /* 调整每个表单项之间的间距 */
}

.statistics {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
}

.stat-card {
    flex: 1;
    margin-right: 10px;
    padding: 20px;
    text-align: center;
}

.stat-title {
    font-size: 16px;
    margin-bottom: 10px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
}
</style>